import { Vec2, screen } from "cc"
import { EventTouch } from "cc"
import { _decorator, Component, Node } from "cc"
import { ClientEvent } from "../framework/ClientEvent"
import { UITransform } from "cc"
import { Label } from "cc"
import { GlobalData } from "../GlobalData"
import { Sprite } from "cc"
import { Tween } from "cc"
import { director } from "cc"
import { resources } from "cc"
import { Prefab } from "cc"
import { instantiate } from "cc"
import ResManager from "../framework/ResManager"
import { AniBossComing } from "../game/AniBossComing"
import { AudioManager } from "../framework/AudioManager"
import { view } from "cc"
import { Size } from "cc"
import { Vec3 } from "cc"
import { tween } from "cc"
import { lerp } from "cc"
import { gtPlayable } from "../GtPlayable"
const { ccclass, property } = _decorator

@ccclass("GameView")
export class GameView extends Component {
  @property(Node)
  nodeGameUI: Node = null!

  @property(Node)
  nodeGameModule: Node = null!

  @property(Node)
  nodeGameBg: Node = null!

  @property(Label)
  labCoinValue: Label = null!

  @property(Label)
  labExpValue: Label = null!

  @property(Label)
  labGemValue: Label = null!

  @property(Label)
  labGameLevelValue: Label = null!

  @property({ type: UITransform, displayName: "血量进度条" })
  uiTranProgress: UITransform = null!

  @property(Node)
  nodeGemMove: Node = null!

  @property(Node)
  nodeDownloadLandscape: Node = null!

  @property(Node)
  nodeDownloadPortrait: Node = null!

  private maxProgressWidth: number = 0

  nodeUiGameBuffView: Node = null
  protected onLoad(): void {
    gtPlayable.gameStart()
    gtPlayable.sendActionScene("scene1_view",1,"用户进入游戏场景")
    this.updateAdapter()
  }

  start() {
    // this.labGameLevelValue.node.alpha = 1
    this.maxProgressWidth = this.uiTranProgress.width
    this.loadUIGameBuffView()

    // this.scheduleOnce(this.onGameOver,3)
  }

  protected onEnable(): void {
    ClientEvent.on("onCoinValueChange", this.onCoinValueChange, this)
    ClientEvent.on("onExpValueChange", this.onExpValueChange, this)
    ClientEvent.on("onGemValueChange", this.onGemValueChange, this)

    ClientEvent.on("onPowerValueChange", this.onPowerValueChange, this)
    ClientEvent.on("onGamePlayerHpChange", this.onGamePlayerHpChange, this)
    ClientEvent.on("onGameLevelChange", this.onGameLevelChange, this)
    ClientEvent.on("onGameStart", this.onGameStart, this)
    ClientEvent.on("onGameOver", this.onGameOver, this)
    ClientEvent.on("createBossComingEffect", this.createBossComingEffect, this)
    ClientEvent.on("onMonsterWaveComplete", this.onMonsterWaveComplete, this)
    ClientEvent.on("onGameMonsterCountChange", this.onGameMonsterCountChange, this)
    ClientEvent.on("onGameCreateGem", this.onGameCreateGem, this)
    ClientEvent.on("onStartBossIsRaging", this.onStartBossIsRaging, this)
    view.on("canvas-resize", this.updateAdapter, this)
    this.nodeDownloadLandscape.on(Node.EventType.TOUCH_START, this.onClickDownload, this)
    this.nodeDownloadPortrait.on(Node.EventType.TOUCH_START, this.onClickDownload, this)
    //
  }

  protected onDisable(): void {
    ClientEvent.off("onCoinValueChange", this.onCoinValueChange, this)
    ClientEvent.off("onExpValueChange", this.onExpValueChange, this)
    ClientEvent.off("onGemValueChange", this.onGemValueChange, this)

    ClientEvent.off("onPowerValueChange", this.onPowerValueChange, this)
    ClientEvent.off("onGamePlayerHpChange", this.onGamePlayerHpChange, this)
    ClientEvent.off("onGameLevelChange", this.onGameLevelChange, this)
    ClientEvent.off("onGameStart", this.onGameStart, this)
    ClientEvent.off("onGameOver", this.onGameOver, this)
    ClientEvent.off("createBossComingEffect", this.createBossComingEffect, this)
    ClientEvent.off("onMonsterWaveComplete", this.onMonsterWaveComplete, this)
    ClientEvent.off("onGameMonsterCountChange", this.onGameMonsterCountChange, this)
    ClientEvent.off("onStartBossIsRaging", this.onStartBossIsRaging, this)
    ClientEvent.off("onGameCreateGem", this.onGameCreateGem, this)

    view.off("canvas-resize", this.updateAdapter, this)
    this.nodeDownloadLandscape.off(Node.EventType.TOUCH_START, this.onClickDownload, this)
    this.nodeDownloadPortrait.off(Node.EventType.TOUCH_START, this.onClickDownload, this)
  }

  private onGameStart() {
    // const nodeLevel = this.labGameLevelValue.node
    // new Tween(nodeLevel).to(0.5, { alpha: 1 }).start()
  }

  private onGameOver() {
    const endingViewPrefab = resources.get("prefabs/endingView", Prefab)
    const endingView = instantiate(endingViewPrefab)
    this.nodeGameUI.addChild(endingView)
    if (this.nodeWarn) {
      this.nodeWarn.destroy()
    }
  }

  private onGameLevelChange() {
    // const curLevel = Math.min(GlobalData.instance.curLevel + 1, GlobalData.instance.levelData.length)
    // this.labGameLevelValue.string = "WAVE " + curLevel + "/" + GlobalData.instance.levelData.length
  }

  private onGamePlayerHpChange() {
    // this.labGamePlayerHpValue.string = GlobalData.instance.gamePlayerHp + "/" + GlobalData.instance.maxGamePlayerHp
    // this.uiTranProgress.width =
    //   (GlobalData.instance.gamePlayerHp / GlobalData.instance.maxGamePlayerHp) * this.maxProgressWidth
  }

  private onGameMonsterCountChange() {
    this.uiTranProgress.width =
      (this.maxProgressWidth * GlobalData.instance.curMonsterCount) / GlobalData.instance.maxMonsterCount
  }

  private timeValue: number = 10
  private current:number = 0
  private onCoinValueChange() {
    this.current = (GlobalData.instance.coinValue - this.currentNumber) / this.timeValue
    this.unschedule(this.coinValueChange)
    this.schedule(this.coinValueChange, 0.02, this.timeValue - 1)
  }

  private currentNumber: number = 0
  private coinValueChange() {
    this.currentNumber += this.current
    this.labCoinValue.string = Math.round(this.currentNumber) + ""
  }

  private onExpValueChange() {
    this.labExpValue.string = GlobalData.instance.expValue + ""
  }

  private onGemValueChange() {
    this.labGemValue.string = GlobalData.instance.gemValue + ""
  }
  private onPowerValueChange() {
    // this.labPowerValue.string = GlobalData.instance.powerValue + ""
  }
  update(deltaTime: number) {
    // let uiTransform:UITransform = this.node.getComponent(UITransform)
    // console.log(uiTransform.width,uiTransform.height)
    // this.labCoinValue.string = Math.round(lerp(this.curCoin,GlobalData.instance.coinValue,0.5)) + ""
    // this.labCoinValue.string = Math.round(this.curCoin) + ""
  }

  public onInitJsonData() {
    ClientEvent.emit("onInitJsonData")
  }

  public onRefuseData() {
    ClientEvent.emit("onRefuseData")
    // while(GlobalData.instance.arrNodeMonster.)
  }

  private createBossComingEffect(index: number) {
    ResManager.instance.loadRes("prefabs/game/gameObject/nodeBossComing", Prefab, (err, prefab: Prefab) => {
      AudioManager.instance.playEffect("sm_warn")
      this.scheduleOnce(() => {
        AudioManager.instance.playEffect("sm_warn")
      }, 1)
      const nodeBossComing = instantiate(prefab)
      // const canvasNode = director.getScene().getChildByName("Canvas")
      const ani: AniBossComing = nodeBossComing.getComponent(AniBossComing)
      ani.init(index)
      this.nodeGameUI.addChild(nodeBossComing)
    })
  }

  private onMonsterWaveComplete() {
    this.labGameLevelValue.string = "WAVE " + (GlobalData.instance.curLevel + 1)
    this.onGameMonsterCountChange()
  }

  private updateAdapter() {
    let winSize = new Size(screen.windowSize.width / view["_scaleX"], screen.windowSize.height / view["_scaleY"])

    if (winSize.width > winSize.height) {
      this.nodeGameModule.scaleXYZ = 1
      this.nodeGameBg.scaleXYZ = 1
      this.nodeDownloadLandscape.active = true  
      this.nodeDownloadPortrait.active = false
    } else {
      this.nodeGameModule.scaleXYZ = 1.7
      this.nodeGameBg.scaleXYZ = winSize.height / winSize.width / this.nodeGameModule.scaleXYZ
      this.nodeDownloadLandscape.active = false
      this.nodeDownloadPortrait.active = true
    }

    if (winSize.width > winSize.height) {
      this.nodeGameUI.scaleXYZ = 1
      // if (winSize.width > 2 * winSize.height) {
      //   this.nodeGameUI.scaleXYZ = 0.8
      // }
    } else {
      if (winSize.height < 1.5 * winSize.width) {
        this.nodeGameUI.scaleXYZ = 1.7
      } else {
        this.nodeGameUI.scaleXYZ = 2.2
      }
    }

    GlobalData.instance.winSize = winSize
  }

  private onClickDownload() {
    gtPlayable.sendActionClick("action_download1","用户点击下载按钮")
    gtPlayable.install()
  }

  private loadUIGameBuffView() {
    // return
    ResManager.instance.loadRes("prefabs/ui/UIGameBuffView", Prefab, (err, prefab: Prefab) => {
      const nodeGameBuffView = instantiate(prefab)
      this.nodeGameUI.addChild(nodeGameBuffView)
    })
  }

  /**宝石特效 */
  private onGameCreateGem(pos: Vec3) {
    ResManager.instance.loadRes("prefabs/game/gameObject/nodeGameGem", Prefab, (err, prefab: Prefab) => {
      if (prefab) {
        const nodeGameGem = instantiate(prefab)
        this.nodeGameUI.addChild(nodeGameGem)
        nodeGameGem.setPosition(pos)
        const time1: number = 0.5
        new Tween(nodeGameGem).by(time1, { positionX: 150 }).start()
        new Tween(nodeGameGem)
          .by(time1 * 0.5, { positionY: 80 }, { easing: "cubicOut" })
          .by(time1 * 0.5, { positionY: -80 }, { easing: "bounceOut" })
          .delay(0.5)
          .call(() => {
            const worldPos = this.nodeGemMove.getWorldPosition()
            const uiTransformParent: UITransform = this.nodeGameUI.getComponent(UITransform)
            const posNode = uiTransformParent.convertToNodeSpaceAR(worldPos)
            new Tween(nodeGameGem)
              .to(0.3, { position: posNode })
              .call(() => {
                GlobalData.instance.gemValue++
                nodeGameGem.destroy()
              })
              .start()
          })
          .start()
      }
    })
  }

  private nodeWarn = null
  private onStartBossIsRaging() {
    // const nodeGameBefore = this.nodeGameUI.getChildByName("nodeGameBefore")
    ResManager.instance.loadRes("prefabs/game/gameObject/nodeWarn", Prefab, (err, prefab: Prefab) => {
      if (prefab) {
        this.nodeWarn = instantiate(prefab)
        this.nodeGameUI.addChild(this.nodeWarn)
        new Tween(this.nodeWarn).to(0.5, { alpha: 0 }).to(0.5, { alpha: 1 }).union().repeat(5).start()
      }
    })
  }
}
